#include "kellipseshape.h"

KEllipseShape::KEllipseShape(QGraphicsItem* parent)
    : KShape(parent)
{
}

KEllipseShape::~KEllipseShape()
{
}

KShapeType KEllipseShape::getShapeType() const
{
    return KShapeType::EllipseShapeType;
}


void KEllipseShape::paint(QPainter* painter, const QStyleOptionGraphicsItem*, QWidget*)
{
    setAllStyle(painter);
    painter->drawEllipse(m_rect);

    if (isSelected()) {
        drawBoundingPreview(painter);
    }
}

QDomElement KEllipseShape::toSvgElement(QDomDocument& doc) const
{
    QDomElement elem = doc.createElement("ellipse");
    QSizeF size = m_rect.size();
    QPointF center = mapToScene(m_rect.center());

    elem.setAttribute("cx", center.x());
    elem.setAttribute("cy", center.y());
    elem.setAttribute("rx", size.width() / 2);
    elem.setAttribute("ry", size.height() / 2);

    elem.setAttribute("fill", getFillColor().name());
    elem.setAttribute("stroke", getLineColor().isValid() ? getLineColor().name() : "#000000");
    elem.setAttribute("stroke-width", QString::number(getLineWidth()));
    QString dash = penStyleToDashArray(getLineStyle());
    if (!dash.isEmpty())
        elem.setAttribute("stroke-dasharray", dash);

    addSvgRotation(elem, m_rect);

    return elem;
}

void KEllipseShape::loadFromSvgElement(const QDomElement& elem)
{
    KShape::loadFromSvgElement(elem);

    qreal cx = elem.attribute("cx").toDouble();
    qreal cy = elem.attribute("cy").toDouble();
    qreal rx = elem.attribute("rx").toDouble();
    qreal ry = elem.attribute("ry").toDouble();

    QPointF center(cx, cy);
    QPointF topLeft = center - QPointF(rx, ry);

    m_startPoint = topLeft;
    m_endPoint = topLeft + QPointF(2 * rx, 2 * ry);
    m_rect = QRectF(0, 0, 2 * rx, 2 * ry);
    setPos(topLeft);
    setRotationFromSvg(elem);
    applySvgStyle(elem);
    updateTransformInfo();
}
void KEllipseShape::refreshTransformInfoFromRect()
{
    QPointF scenePos = this->pos();
    QSizeF size = m_rect.size();
    m_startPoint = scenePos;
    m_endPoint = scenePos + QPointF(size.width(), size.height());
    updateTransformInfo();
}

std::unique_ptr<KExportShape> KEllipseShape::clone() const {
    auto* copy = new KEllipseShape();
    copy->setRect(this->getRect());
    copy->setFillColor(this->getFillColor());
    copy->setLineColor(this->getLineColor());
    copy->setLineWidth(this->getLineWidth());
    copy->setLineStyle(this->getLineStyle());
    copy->setRotation(this->rotation());
    copy->setStartPoint(this->getStartPoint() + QPointF(20, 20));
    copy->setEndPoint(this->getEndPoint() + QPointF(20, 20));
    copy->finalizeItemGeometry();
    return std::unique_ptr<KExportShape>(copy);
}
